package br.elsa.survey.view.beans.managed;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;

import br.elsa.survey.domain.qualifiers.NewEntity;
import br.elsa.survey.domain.questions.CheckboxOption;
import br.elsa.survey.domain.questions.CheckboxQuestion;
import br.elsa.survey.domain.questions.QuestionsFactory;
import br.elsa.survey.services.QuestionService;
import br.elsa.survey.view.messages.ViewMessages;

/**
 * Component that handles all event from the view
 * /views/questions/multipleChoice/createFormView.xhtml
 * 
 * <p>
 * This component delegates to the business logic service
 * {@link QuestionService} the responsibility of create a new
 * {@link CheckboxQuestion} into the database.
 * </p>
 * 
 * @author diego
 * @since 2010-10-03
 */
@ViewScoped
@ManagedBean
public class CheckboxQuestionCreationView extends AbstractQuestionCreationView implements Serializable {

	private static final long serialVersionUID = -4364670220036529072L;

	/**
	 * Injects a new instance of {@link CheckboxQuestion}, created by
	 * {@link QuestionsFactory}.
	 */
	@Inject
	@NewEntity
	private CheckboxQuestion newQuestion;

	/**
	 * Default constructor used by CDI mechanisms to create a new instance of
	 * this class.
	 */
	public CheckboxQuestionCreationView() {

	}

	/**
	 * Constructor used by Test Classes to inject Mock dependencies.
	 */
	public CheckboxQuestionCreationView(CheckboxQuestion newQuestion, QuestionsFactory questionsFactory, QuestionService questionService, ViewMessages viewMessages) {

		super(questionsFactory, questionService, viewMessages);
		this.newQuestion = newQuestion;
	}

	/**
	 * Add a new {@link CheckboxOption} to the
	 * {@link CheckboxQuestionCreationView#newQuestion} instance.
	 */
	public void addNewOption() {

		newQuestion.createNewEmptyOption();
	}

	/**
	 * Removes the last created {@link CheckboxOption} from the
	 * {@link CheckboxQuestionCreationView#newQuestion} instance.
	 */
	public void removeLastChoice() {

		if (newQuestion.getOptions().size() > 1) {
			newQuestion.removeLastOption();
		}
	}

	/**
	 * Aditional input validation before creating the question TODO study a way
	 * of put this validation logic in a separated component, may be an
	 * interceptor...
	 */
	@Override
	public void createQuestion() {

		if (newQuestion.getMinNumberChosenOptions() <= newQuestion.getOptions().size()) {
			super.createQuestion();

		} else {
			viewMessages.addErrorMessage("The number of MIN chosen options can not be greater than the options cout.");
		}
	}

	@Override
	public void resetViewState() {
		this.newQuestion = questionsFactory.createCheckboxQuestion();
	}

	@Override
	public CheckboxQuestion getNewQuestion() {
		return newQuestion;
	}

}
